package models;

import helpers.GeneralHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

import entities.Domain;

public class DomainModel {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String prefix = "domain_";

	private static DomainModel instance = null;
	
	public static DomainModel getInstance() {
		if (instance == null) {
			instance = new DomainModel();
		}
		
		return instance;
	}
	
	private DomainModel() {
		try {
			ObjectifyService.register(Domain.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		cache = GeneralHelper.getCache();
		ofy = GeneralHelper.getObjectify();
	}
	
	public Domain get(String domainName) {
		Domain domain = new Domain();
		try {
			domain = ofy.get(new Key<Domain>(Domain.class, domainName));
		} catch (Exception e) {
			domain = null;
		}
		return domain;
	}
	
	public void insert(Domain domain) {
		ofy.put(domain);
	}
	
	public List<Domain> getBlacklistDomains(int page, int limit) {
		List<Domain> domains = new ArrayList<Domain>();
		
		int start = (page - 1) * limit;
		domains = ofy.query(Domain.class).filter("status", -1).limit(limit).offset(start).list();
		
		if (domains == null) {
			domains = new ArrayList<Domain>();
		}
		
		return domains;
	}
	
	public void delete(Domain domain) {
		ofy.delete(domain);
	}
	
	public List<Domain> getByListId(List<String> ids) {
		List<Domain> domains = new ArrayList<Domain>();
		
		try {
			Map<String, Domain> ars = ofy.get(Domain.class, ids);
			
			for (Map.Entry<String, Domain> entry : ars.entrySet()) {
				if (entry.getValue() != null) {
					domains.add(entry.getValue());
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		return domains;
	}
}
